﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting.Internal;
using Newtonsoft.Json;
using NLog;
using SealManagement.Common;
using SealManagement.Extensions;
using SealManagement.Models;
using SealManagement.SqlData;

namespace SealManagement.Controllers
{
    public class InfoLogController : Controller
    {
        private readonly SignContext _context;
        private readonly IHostingEnvironment _hostingEnvironment;
        static Logger logger = LogManager.GetCurrentClassLogger();
        private int usertype = (int)userType.User;

        public InfoLogController(SignContext context, IHostingEnvironment hostingEnvironment)
        {
            _context = context;
            _hostingEnvironment = hostingEnvironment;
        }

        // GET: InfoLog
        //[Authorize(Roles = "User,SignMaker")]
        //public async Task<IActionResult> Index()
        //{
        //    //User.FindFirst(p=>p.Value)
        //    var roleId = User.FindFirst(ClaimTypes.Sid).Value;
        //    var roleType = User.FindFirst(ClaimTypes.Role).Value;

        //    if (roleType == userType.SignMaker.ToString())
        //    {
        //        usertype = 1;
        //        //return View(await _context.InfoLogs.Where(p => p.UserType == (int)userType.SignMaker && p.UserName == User.Identity.Name).ToListAsync());
        //        return View(await _context.InfoLogs.Where(p => p.UserType == (int)userType.SignMaker && p.UserId == Convert.ToInt32(roleId)).ToListAsync());
        //    }
        //    return View(await _context.InfoLogs.ToListAsync());
        //}
        [Authorize(Roles = "User,SignMaker")]
        public async Task<IActionResult> Index()
        {
            //var total = await _context.Users.CountAsync();
            ViewData["Role"] = User.FindFirst(ClaimTypes.Role).Value;
            var guid = Guid.NewGuid();
            ViewData["ValidateCode"] = guid.ToString();
            HttpContext.Response.Cookies.Append("ValidateCode",
                Convert.ToBase64String(ToolClass.Encrypt(Encoding.UTF8.GetBytes(guid.ToString()))));
            return View();
        }
        [Authorize(Roles = "User,SignMaker")]
        [HttpPost]
        public async Task<IActionResult> Index(int PageSize = 10, int PageIndex = 1)
        {
            //var users = await _context.Users.Skip(PageSize * (PageIndex - 1)).Take(PageSize * PageIndex).ToListAsync();
            //var total = await _context.Users.CountAsync();
            //return Json(new { state = resultType.Success, data = users, total = total });

            var total = 0;
            var infoList = new List<InfoLog>();
            var roleId = User.FindFirst(ClaimTypes.Sid).Value;
            var roleType = User.FindFirst(ClaimTypes.Role).Value;
            if (roleType == userType.SignMaker.ToString())
            {
                usertype = 1;
                //return View(await _context.InfoLogs.Where(p => p.UserType == (int)userType.SignMaker && p.UserName == User.Identity.Name).ToListAsync());
                infoList = await _context.InfoLogs.Where(p => p.UserType == usertype && p.UserId == Convert.ToInt32(roleId)).Skip(PageSize * (PageIndex - 1)).Take(PageSize).ToListAsync();
                total = await _context.InfoLogs.Where(p => p.UserType == usertype && p.UserId == Convert.ToInt32(roleId)).CountAsync();
            }
            else
            {
                infoList = await _context.InfoLogs.Skip(PageSize * (PageIndex - 1)).Take(PageSize).ToListAsync();
                total = await _context.InfoLogs.CountAsync();
            }
            return Json(new { state = resultType.Success, data = infoList, total = total });
        }

        // GET: InfoLog/Details/5
        //public async Task<IActionResult> Details(int? id)
        //{
        //    if (id == null)
        //    {
        //        return NotFound();
        //    }

        //    var infoLog = await _context.InfoLogs
        //        .FirstOrDefaultAsync(m => m.Id == id);
        //    if (infoLog == null)
        //    {
        //        return NotFound();
        //    }

        //    return View(infoLog);
        //}

        // GET: InfoLog/Create
        //public IActionResult Create()
        //{
        //    return View();
        //}

        // POST: InfoLog/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public async Task<IActionResult> Create([Bind("Id,UserName,UserType,ManageType,CreateDate,Remark")] InfoLog infoLog)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        _context.Add(infoLog);
        //        await _context.SaveChangesAsync();
        //        return RedirectToAction(nameof(Index));
        //    }
        //    return View(infoLog);
        //}

        // GET: InfoLog/Edit/5
        //public async Task<IActionResult> Edit(int? id)
        //{
        //    if (id == null)
        //    {
        //        return NotFound();
        //    }

        //    var infoLog = await _context.InfoLogs.FindAsync(id);
        //    if (infoLog == null)
        //    {
        //        return NotFound();
        //    }
        //    return View(infoLog);
        //}

        // POST: InfoLog/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public async Task<IActionResult> Edit(int id, [Bind("Id,UserName,UserType,ManageType,CreateDate,Remark")] InfoLog infoLog)
        //{
        //    if (id != infoLog.Id)
        //    {
        //        return NotFound();
        //    }

        //    if (ModelState.IsValid)
        //    {
        //        try
        //        {
        //            _context.Update(infoLog);
        //            await _context.SaveChangesAsync();
        //        }
        //        catch (DbUpdateConcurrencyException)
        //        {
        //            if (!InfoLogExists(infoLog.Id))
        //            {
        //                return NotFound();
        //            }
        //            else
        //            {
        //                throw;
        //            }
        //        }
        //        return RedirectToAction(nameof(Index));
        //    }
        //    return View(infoLog);
        //}

        // GET: InfoLog/Delete/5
        //public async Task<IActionResult> Delete(int? id)
        //{
        //    if (id == null)
        //    {
        //        return NotFound();
        //    }

        //    var infoLog = await _context.InfoLogs
        //        .FirstOrDefaultAsync(m => m.Id == id);
        //    if (infoLog == null)
        //    {
        //        return NotFound();
        //    }

        //    return View(infoLog);
        //}

        // POST: InfoLog/Delete/5
        //[HttpPost, ActionName("Delete")]
        //[ValidateAntiForgeryToken]
        //public async Task<IActionResult> DeleteConfirmed(int id)
        //{
        //    var infoLog = await _context.InfoLogs.FindAsync(id);
        //    _context.InfoLogs.Remove(infoLog);
        //    await _context.SaveChangesAsync();
        //    return RedirectToAction(nameof(Index));
        //}

        private bool InfoLogExists(int id)
        {
            return _context.InfoLogs.Any(e => e.Id == id);
        }
        /// <summary>
        /// 日志备份
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles = "User")]
        public async Task<IActionResult> FileBackUp()
        {
            var infoLogs = await _context.InfoLogs.ToListAsync();
            var infoLogBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(infoLogs));
            logger.Info($"{User.Identity.Name}进行了日志备份");
            _context.InfoLogs.Add(new InfoLog()
            {
                UserId = Convert.ToInt32(User.FindFirst(ClaimTypes.Sid).Value),
                UserName = User.Identity.Name,
                CreateDate = DateTime.Now.ToString(),
                UserType = (int)usertype,
                Remark = $"{User.Identity.Name}进行了备份日志",
                ManageType = manageType.BackUp.ToString()
            });
            await _context.SaveChangesAsync();
            return File(infoLogBytes, "text/plain", $"InfoLog_BackUp_{DateTime.Now.ToString("yyyyMMddHHmmss")}.txt");
        }
        /// <summary>
        /// 日志恢复
        /// </summary>
        [HttpPost]
        [Authorize(Roles = "User")]
        //public async Task<IActionResult> FileRecover(IFormFile file)
        public async Task<IActionResult> FileRecover(string EncryptData)
        {
            if (!Define.IsChecked)
            {
                return Json(new { state = resultType.Error, message = "系统未经自检，请先执行自检后操作" });
            }
            var jsonBack = ToolClass.EncryptTransit(EncryptData);
            //if (string.IsNullOrEmpty(jsonBack))
            //{
            //    return Json(new { state = resultType.Error, message = "参数错误" });
            //}
            if (int.TryParse(jsonBack, out var errorCodeValue))
            {
                var errorCode = (ErrorCode)errorCodeValue;
                return Json(new { state = resultType.Error, message = $"错误码：{errorCodeValue}，错误信息：{ToolClass.GetDescription(errorCode)}" });
            }
            string webRootPath = _hostingEnvironment.WebRootPath;
            FileModel fileModel = new FileModel();
            try
            {
                fileModel = JsonConvert.DeserializeObject<FileModel>(jsonBack);
            }
            catch (Exception)
            {
                return Json(new { state = resultType.Error, message = "文件数据异常" });
            }

            #region cookie验证
            var guidStr = "";
            if (!HttpContext.Request.Cookies.TryGetValue("ValidateCode", out guidStr))
            {
                return Json(new { state = resultType.Error, message = "cookie未设置，请联系管理员" });
            }
            var guidFromCookie = Encoding.UTF8.GetString(ToolClass.Decrypt(Convert.FromBase64String(guidStr)));
            if (!string.Equals(guidFromCookie, fileModel.ValidateCode, StringComparison.OrdinalIgnoreCase))
            {
                return Json(new { state = resultType.Error, message = "cookie不正确，请刷新页面后重试" });
            }
            #endregion

            var fileBase64Str = fileModel.FileContent;
            byte[] fileBytes = null;
            try
            {
                fileBytes = Convert.FromBase64String(fileBase64Str);
                //fileBytes = Encoding.UTF8.GetBytes(fileBase64Str);
            }
            catch (Exception)
            {
                return Json(new { state = resultType.Error, message = "文件编码错误" });
            }
            //var files = Request.Form.Files;

            //if (files != null && files.Count() > 0)
            //{
            //var file = files[0];
            //var fullfilename = file.FileName;
            //string fileName = fullfilename.Substring(fullfilename.LastIndexOf("\\") + 1, (fullfilename.LastIndexOf(".") - fullfilename.LastIndexOf("\\") - 1)); //文件名
            //string fileExt = fullfilename.Substring(fullfilename.LastIndexOf(".") + 1, (fullfilename.Length - fullfilename.LastIndexOf(".") - 1)); //扩展名
            //long fileSize = file.Length; //获得文件大小，以字节为单位
            //string newFileName = fileName + $"_{DateTime.Now.ToString("yyyyMMddHHmmss")}" + "." + fileExt;
            var newFileName = fileModel.FileName + $"_{DateTime.Now.ToString("yyyyMMddHHmmss")}" + "." + fileModel.FileSuffix;
            var filePath = Path.Combine(webRootPath, "upload", newFileName);
            var fileLogStr = string.Empty;
            using (var stream = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                //await file.CopyToAsync(stream);
                stream.Write(fileBytes, 0, fileBytes.Length);
            }
            //var fileLogBytes = new byte[1024];
            //var len = 0;
            //var sb = new StringBuilder();
            //using (FileStream readstream = System.IO.File.OpenRead(filePath))
            //{
            //    while (true)
            //    {
            //        len = readstream.Read(fileLogBytes, 0, fileLogBytes.Length);
            //        if (len > 0)
            //        { 
            //            sb.Append(Encoding.UTF8.GetString(fileLogBytes));
            //            fileLogBytes = new byte[1024];
            //        }
            //        else
            //            break;
            //    }
            //}
            //fileLogStr = sb.ToString();
            string str = "";
            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                    while (!sr.EndOfStream)
                    {
                        str = sr.ReadLine();
                    }
            }
            var infoLogs = new List<InfoLog>();
            try
            {
                infoLogs = JsonConvert.DeserializeObject<List<InfoLog>>(str);
            }
            catch (Exception e)
            {
                return Json(new { state = resultType.Error, message = "文件内容非日志记录类型内容或文件内容有误" });
            }
            var ids = new List<int>();
            foreach (var item in infoLogs)
            {
                ids.Add(item.Id);
            }
            _context.InfoLogs.RemoveRange(_context.InfoLogs.Where(p => ids.Contains(p.Id)).ToArray());
            _context.InfoLogs.AddRange(infoLogs);

            logger.Info($"{User.Identity.Name}进行了日志恢复");
            _context.InfoLogs.Add(new InfoLog()
            {
                UserId = Convert.ToInt32(User.FindFirst(ClaimTypes.Sid).Value),
                UserName = User.Identity.Name,
                CreateDate = DateTime.Now.ToString(),
                UserType = (int)usertype,
                Remark = $"{User.Identity.Name}对日志{newFileName}进行了恢复",
                ManageType = manageType.FileRecover.ToString()
            });
            await _context.SaveChangesAsync();
            System.IO.File.Delete(filePath);
            return Json(new { state = resultType.Success, message = "文件恢复成功", obj = infoLogs });
            //}
            //else
            //{
            //return Json(new { State = "Error", Message = "未选择文件" });
            //}
        }

        /// <summary>
        /// 备份全库
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles = "User")]
        public async Task<IActionResult> BackUpAll()
        {
            var rootPath = _hostingEnvironment.ContentRootPath;
            string webRootPath = _hostingEnvironment.WebRootPath;
            //var filePath = Path.Combine(webRootPath, "upload");
            //var filePath = Path.Combine(webRootPath, "upload");
            //if (!Directory.Exists(filePath))
            //{
            //    Directory.CreateDirectory(filePath);
            //}
            //#region 以往方法
            //System.IO.File.Copy(Path.Combine(rootPath, "testnetcore.db"), Path.Combine(filePath, desFileName));
            byte[] dbBytes = null;
            ////FileStream fileStream;
            //using (FileStream fileStream = new FileStream(Path.Combine(filePath, desFileName), FileMode.Open))
            //{
            //    using (StreamReader reader = new StreamReader(fileStream))
            //    {
            //        dbBytes = Encoding.UTF8.GetBytes(reader.ReadToEnd());
            //    }
            //}
            //#endregion
            try
            {
                SQLiteConnection cnSource = new SQLiteConnection(@"Data Source=testnetcore.db");
                //库名称嵌入链接,库名称字符串前$符引起数据库异常
                SQLiteConnection cnDest = new SQLiteConnection(@"Data Source=test.db");
                try
                {
                    cnDest.Open();
                    cnSource.Open();

                    cnSource.BackupDatabase(cnDest, "main", "main", -1, null, 0);
                    cnDest.Close();
                    cnSource.Close();

                    //if (System.IO.File.Exists(configMng.backUpPath + @"\" + destDBFileNameProcess))
                    //{
                    //    destDBFileName = destDBFileName.Insert(index, DateTime.Now.ToString("yyyyMMddHHmmss"));
                    //    File.Move(configMng.backUpPath + @"\" + destDBFileNameProcess, configMng.backUpPath + @"\" + destDBFileName);
                    //}
                }
                catch (Exception e)
                {
                    //LogHelper.WiteLog("SQLiteBackUpService backup faild!");
                    if (cnDest.State == ConnectionState.Open)
                    {
                        cnDest.Close();
                    }
                    if (cnSource.State == ConnectionState.Open)
                    {
                        cnSource.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                return Json(new { state = resultType.Error, message = "参数异常" });
            }
            //using (FileStream fileStream = new FileStream(Path.Combine(rootPath, "test.db"), FileMode.Open))
            //{
            //    using (StreamReader reader = new StreamReader(fileStream))
            //    {
            //        //dbBytes = Encoding.ASCII.GetBytes(reader.ReadToEnd());
            //    }
            //}
            dbBytes = System.IO.File.ReadAllBytes(Path.Combine(rootPath, "test.db"));
            System.IO.File.Delete(Path.Combine(rootPath, "test.db"));
            logger.Info($"{User.Identity.Name}进行了全库备份");
            _context.InfoLogs.Add(new InfoLog()
            {
                UserId = Convert.ToInt32(User.FindFirst(ClaimTypes.Sid).Value),
                UserName = User.Identity.Name,
                CreateDate = DateTime.Now.ToString(),
                UserType = (int)usertype,
                Remark = $"{User.Identity.Name}进行了全库备份",
                ManageType = manageType.BackUp.ToString()
            });
            await _context.SaveChangesAsync();
            return File(dbBytes, "text/plain", $"test_{DateTime.Now.ToString("yyyyMMddHHmmss")}.db");
        }
        /// <summary>
        /// 恢复全库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles = "User")]
        public async Task<IActionResult> FileRecoverAll(string EncryptData)
        {
            if (!Define.IsChecked)
            {
                return Json(new { state = resultType.Error, message = "系统未经自检，请先执行自检后操作" });
            }
            var jsonBack = ToolClass.EncryptTransit(EncryptData);
            //if (string.IsNullOrEmpty(jsonBack))
            //{
            //    return Json(new { state = resultType.Error, message = "参数错误" });
            //}
            if (int.TryParse(jsonBack, out var errorCodeValue))
            {
                var errorCode = (ErrorCode)errorCodeValue;
                return Json(new { state = resultType.Error, message = $"错误码：{errorCodeValue}，错误信息：{ToolClass.GetDescription(errorCode)}" });
            }
            string webRootPath = _hostingEnvironment.WebRootPath;
            var rootPath = _hostingEnvironment.ContentRootPath;
            FileModel fileModel = new FileModel();
            try
            {
                fileModel = JsonConvert.DeserializeObject<FileModel>(jsonBack);
            }
            catch (Exception)
            {
                return Json(new { state = resultType.Error, message = "文件数据异常" });
            }
            #region cookie验证
            var guidStr = "";
            if (!HttpContext.Request.Cookies.TryGetValue("ValidateCode", out guidStr))
            {
                return Json(new { state = resultType.Error, message = "cookie未设置，请联系管理员" });
            }
            var guidFromCookie = Encoding.UTF8.GetString(ToolClass.Decrypt(Convert.FromBase64String(guidStr)));
            if (!string.Equals(guidFromCookie, fileModel.ValidateCode, StringComparison.OrdinalIgnoreCase))
            {
                return Json(new { state = resultType.Error, message = "cookie不正确，请刷新页面后重试" });
            }
            #endregion
            var fileBase64Str = fileModel.FileContent;
            byte[] fileBytes = null;
            try
            {
                fileBytes = Convert.FromBase64String(fileBase64Str);
                //fileBytes = Encoding.UTF8.GetBytes(fileBase64Str);
            }
            catch (Exception)
            {
                return Json(new { state = resultType.Error, message = "文件编码错误" });
            }

            //var files = Request.Form.Files;

            //if (files != null && files.Count() > 0)
            {
                //var file = files[0];
                //var fullfilename = file.FileName;
                //string fileName = fullfilename.Substring(fullfilename.LastIndexOf("\\") + 1, (fullfilename.LastIndexOf(".") - fullfilename.LastIndexOf("\\") - 1)); //文件名
                //string fileExt = fullfilename.Substring(fullfilename.LastIndexOf(".") + 1, (fullfilename.Length - fullfilename.LastIndexOf(".") - 1)); //扩展名
                //long fileSize = file.Length; //获得文件大小，以字节为单位
                //string newFileName = fileName.Split(new char[] { '_' })[0] + "." + fileExt;
                var newFileName = fileModel.FileName + $"_{DateTime.Now.ToString("yyyyMMddHHmmss")}" + "." + fileModel.FileSuffix;
                //var filePath = webRootPath + "\\upload\\" + newFileName;
                var fileLogStr = string.Empty;
                var desPath = Path.Combine(rootPath, "testnetcore.db");
                System.IO.File.Delete(desPath);
                using (var stream = new FileStream(desPath, FileMode.OpenOrCreate))
                {
                    //await file.CopyToAsync(stream);
                    stream.Write(fileBytes, 0, fileBytes.Length);
                }

                logger.Info($"{User.Identity.Name}进行了全库恢复");
                _context.InfoLogs.Add(new InfoLog()
                {
                    UserId = Convert.ToInt32(User.FindFirst(ClaimTypes.Sid).Value),
                    UserName = User.Identity.Name,
                    CreateDate = DateTime.Now.ToString(),
                    UserType = (int)usertype,
                    Remark = $"{User.Identity.Name}对全库进行了恢复",
                    ManageType = manageType.FileRecover.ToString()
                });
                await _context.SaveChangesAsync();
                return Json(new { state = resultType.Success, message = "文件恢复成功" });
            }
            //else
            //{
            //    return Json(new { State = "Error", Message = "未选择文件" });
            //}
        }

        //获取最近创建的文件名和创建时间
        //如果没有指定类型的文件，返回null
        static FileInfo GetLatestFileInfo(string dir, string ext)
        {
            List<FileInfo> list = new List<FileInfo>();
            DirectoryInfo d = new DirectoryInfo(dir);
            foreach (FileInfo fi in d.GetFiles())
            {
                if (fi.Extension.ToUpper() == ext.ToUpper())
                {
                    list.Add(fi);
                }
            }
            var qry = from x in list
                      orderby x.CreationTime
                      select x;
            return qry.LastOrDefault();
        }

        /// <summary>
        /// 随机数接口
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> ReturnValidateCode()
        {
            var guid = Guid.NewGuid();
            HttpContext.Response.Cookies.Append("ValidateCode",
                Convert.ToBase64String(ToolClass.Encrypt(Encoding.UTF8.GetBytes(guid.ToString()))));
            return Json(new { state = 200, ValidateCode = guid });
        }

        /// <summary>
        /// 分离出的备份页面
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Backup()
        {
            return View();
        }

        public IActionResult GetCurrInfoList()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> GetCurrInfoList(string selectDate, int PageSize = 10, int PageIndex = 1)
        {
            string _selectDate = selectDate;
            List<string> logItems = null;
            var total = 0;
            if (string.IsNullOrEmpty(_selectDate))
            {
                _selectDate = DateTime.Now.ToShortDateString();
            }
            var rootPath = _hostingEnvironment.ContentRootPath;
            var logPath = Path.Combine(rootPath, $"nlog-own-{_selectDate}.log");
            if (!System.IO.File.Exists(logPath))
            {
                return Json(new { state = resultType.Error, message = "不存在当天日志" });
            }
            using (StreamReader sr = new StreamReader(logPath))
            {
                var content = sr.ReadToEnd();
                var logList = content.Split(new string[] { "\n" }, StringSplitOptions.None);
                total = logList.Count();
                logItems = logList
                    .Skip(PageSize * (PageIndex - 1)).Take(PageSize).ToList();
            }
            return Json(new { state = resultType.Success, message = "获取成功", data = logItems, total = total });
        }

        public async Task<IActionResult> DelLogFile(string selectDate)
        {
            if (string.IsNullOrEmpty(selectDate))
            {
                return Json(new { state = resultType.Error, message = "所选日期不能为空" });
            }
            var rootPath = _hostingEnvironment.ContentRootPath;
            var ownLogPath = Path.Combine(rootPath, $"nlog-own-{selectDate}.log");
            var allLogPath = Path.Combine(rootPath, $"nlog-all-{selectDate}.log");
            if (!System.IO.File.Exists(ownLogPath) || !System.IO.File.Exists(allLogPath))
            {
                return Json(new { state = resultType.Error, message = "不存在该天日志" });
            }
            try
            {
                System.IO.File.Delete(ownLogPath);
                System.IO.File.Delete(allLogPath);
            }
            catch (Exception e)
            {
                logger.Info($"删除日期为{selectDate}的日志失败");
                return Json(new { state = resultType.Error, message = $"删除日期为{selectDate}的日志失败，{e.Message}" });
            }
            logger.Info($"{User.Identity.Name}删除了日期为{selectDate}的日志");
            _context.InfoLogs.Add(new InfoLog()
            {
                UserId = Convert.ToInt32(User.FindFirst(ClaimTypes.Sid).Value),
                UserName = User.Identity.Name,
                CreateDate = DateTime.Now.ToString(),
                UserType = (int)usertype,
                Remark = $"{User.Identity.Name}删除了日期为{selectDate}的日志",
                ManageType = manageType.DownLoadFile.ToString()
            });
            await _context.SaveChangesAsync();
            return Json(new { state = resultType.Success, message = "删除成功" });
        }

        public async Task<IActionResult> DownLogFile(string selectDate)
        {
            if (string.IsNullOrEmpty(selectDate))
            {
                return Json(new { state = resultType.Error, message = "所选日期不能为空" });
            }
            var rootPath = _hostingEnvironment.ContentRootPath;
            var ownLogPath = Path.Combine(rootPath, $"nlog-own-{selectDate}.log");
            if (!System.IO.File.Exists(ownLogPath))
            {
                return Json(new { state = resultType.Error, message = "不存在该天日志" });
            }
            byte[] infoLogBytes = null;
            try
            {
                using (StreamReader sr = new StreamReader(ownLogPath))
                {
                    var content = sr.ReadToEnd();
                    var logList = content.Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();
                    infoLogBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(logList));
                }
            }
            catch (Exception e)
            {
                logger.Info($"下载日期为{selectDate}的日志失败");
                return Json(new { state = resultType.Error, message = $"下载日期为{selectDate}的日志失败，{e.Message}" });
            }
            logger.Info($"{User.Identity.Name}下载了日期为{selectDate}的日志");
            _context.InfoLogs.Add(new InfoLog()
            {
                UserId = Convert.ToInt32(User.FindFirst(ClaimTypes.Sid).Value),
                UserName = User.Identity.Name,
                CreateDate = DateTime.Now.ToString(),
                UserType = (int)usertype,
                Remark = $"{User.Identity.Name}下载了日期为{selectDate}的日志",
                ManageType = manageType.DownLoadFile.ToString()
            });
            await _context.SaveChangesAsync();
            return File(infoLogBytes, "text/plain", $"InfoLog_DownLoad_{selectDate}.txt");
        }
    }
}
